package acs.controller;

import acs.collection.Params;
import acs.constant.Constant;
import acs.constant.EventType;
import acs.timer.SoftTimer;
import acs.util.CacheUtil;
import acs.util.CollectionUtil;
import acs.util.DbUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

public class AcsController implements MessageObserver {
	private static AcsController acsController = new AcsController();
	private static Logger logger = LoggerFactory.getLogger(AcsController.class);

	private static final int STATE_INIT = 1;
	private static final int STATE_WAITING_OFFER = 2;// 加载数据中
	private static final int STATE_DATA_LOADED = 4;
	private int currentState = STATE_INIT;// 状态
	private CompletableFuture<Void> queryOffferFuture ;

	public static AcsController getInstance() {
		return acsController;
	}

	@Override
	public void handle(int eventType, Params param) {
		switch (eventType) {
		case EventType.QUERY_CACHE:
			param.put("duration", 2);
			param.put("timeUnit", TimeUnit.SECONDS);
			this.loadOffer(param);
			break;
		case EventType.TIMEOUT_WHEN_GET_TARGET_OFFER:
			handleTargetOfferTimeOut(param);
			break;
		case EventType.RESPONSE_FOR_QUERY_CACHE:
			handleTargetOffer(param);
			break;
		default: {
			logger.error("Can't handle event:{}", eventType);
			break;
		}
		}
	}
	
	private void handleTargetOfferTimeOut(Params param) {
		switch (currentState) {
		case STATE_WAITING_OFFER:
			System.out.println("请求服务端offer超时了");
			boolean result = queryOffferFuture.cancel(false);
			if(result) {
				System.out.println("请求offer任务取消");
			}else {
				System.out.println("请求offer任务取消 失败");
			}
			this.currentState=STATE_INIT;
			break;
		case STATE_DATA_LOADED:
			System.out.println("请求服务端offer成功，不进行取消请求offer任务");
			break;
		}
		
	}

	private void handleTargetOffer(Params param) {
		if(currentState == STATE_WAITING_OFFER) {
			Map<String,Object> offerMap = param.get(Constant.TRANSFER_OFFER);
			if(CollectionUtil.isEmpty(offerMap)) {
				System.out.println("没有查到offers");
				return ;
			}
			CacheUtil.getInstance().saveCache(offerMap);
			this.currentState = STATE_DATA_LOADED;// 设置当前状态为查到了offer
		}
		
	}

	private void loadOffer(Params param) {
		System.out.println("异步查offer");
		//异步 获取offer
		queryOffferFuture = CompletableFuture.runAsync(() -> {
			DbUtil.getInstance().loadOffer(param);
		});
		
		SoftTimer.getInstance().startTimer(1*1000, EventType.TIMEOUT_WHEN_GET_TARGET_OFFER);
		// 设置超时
		this.currentState = STATE_WAITING_OFFER;
	}

}
